﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Pb;
using System.Linq;
using UnityEngine.SceneManagement;


public class XTJGame :Game {
   
    EginUser user = EginUser.Instance;
    EginXTJ xtj = EginXTJ.Instance;
    private int uid;

    public List<XTJUser> xtjUsers;
    public GameObject Root;


    public GameObject exitBtn;
    public GameObject MoneyBtn;
    public GameObject SetBtn;
    public GameObject readyBtn;
    public GameObject QiangZhuang;
   
    public GameObject SetSaizi;//进行掷骰子操作

    #region 押注
    public GameObject ShunMen;
    public GameObject ShunJiao;
    public GameObject Tang;
    public GameObject Tianmen;
    public GameObject Daomen;
    public GameObject Daojiao;

    public long betCoinCount;//下注金币
    public int Direction;//下注方位
    //某个方位的总的筹码数显示框
    public List<UILabel> poolChipsCountLabels;
    //某个方位的自己下的筹码数显示框
    public List<UILabel> ownChipsCountLabels;
    //public List<long> poolChipsCountList;
    public List<long> ownChipsCountList;
    public GameObject stopBet;

    public GameObject ChipPre;//下注的筹码预制体；
    public GameObject cardsPre;//发的牌的预设
    //发牌位置
    public Dictionary<int,GameObject> dealCardsPosDic = new Dictionary<int,GameObject>();
    //所发的牌
    public Dictionary<int,GameObject> dealCardsDic = new Dictionary<int,GameObject>();

    //所掷点数之和
    public int diceSum;
    public GameObject chipParent;//筹码父物体
    #endregion

    //音效
    public List<AudioClip> effectBgList;

    // Use this for initialization
    void Awake()
    {
       
        UIEventListener.Get(exitBtn).onClick = ButtonOnclick;
        UIEventListener.Get(MoneyBtn).onClick = ButtonOnclick;
        UIEventListener.Get(SetBtn).onClick = ButtonOnclick;
        UIEventListener.Get(readyBtn).onClick = ButtonOnclick;
        UIEventListener.Get(QiangZhuang).onClick = ButtonOnclick;
        
        UIEventListener.Get(ShunMen).onClick = ButtonOnclick;
        UIEventListener.Get(ShunJiao).onClick = ButtonOnclick;
        UIEventListener.Get(Tang).onClick = ButtonOnclick;
        UIEventListener.Get(Tianmen).onClick = ButtonOnclick;
        UIEventListener.Get(Daomen).onClick = ButtonOnclick;
        UIEventListener.Get(Daojiao).onClick = ButtonOnclick;

    }
    void Start () {
        uid = int.Parse(user.Uid);

        LoadUser();//加载玩家信息
        base.StartGameSocket();
        SocketManager.Instance.socketListener = this;
        
        xtj.currentChip = xtj.chipList[0];
      
        if(xtj.isReady == true){
            readyBtn.SetActive(true);
        }


    }
	void ButtonOnclick(GameObject Btn)
    {
        if(Btn.name== "ExitBtn")
        {
            PaiLeaveRoundRequest message = new PaiLeaveRoundRequest { };
            SocketManager socketManager = SocketManager.Instance;
            socketManager.SendProtobuf1(message, MsgId.PaiLeaveRoundRequest);
        }
        else if(Btn.name== "MoneyBtn")
        {
            GameObject AddMoney = NGUITools.AddChild(GameObject.Find("UI Root").gameObject, (GameObject)(Resources.Load(HallPrafabPath.AddMoney)));
            Add_MoneyModel addMoneyModel = AddMoney.GetComponent<Add_MoneyModel>();
            addMoneyModel.PayForGold.SetActive(true);
            addMoneyModel.PayForRoomCard.SetActive(false);
            addMoneyModel.TransferAccount.SetActive(false);
            addMoneyModel.GoldBtnBg.SetActive(true);
            addMoneyModel.RoomCardBtnBg.SetActive(false);
            addMoneyModel.TransfBtnBg.SetActive(false);
        }
        else if (Btn.name == "SetBtn")
        {
            NGUITools.AddChild(this.gameObject, (GameObject)(Resources.Load(GameXTJPrafabPath.XTJSetPanel)));
        }
        else if (Btn.name == "ReadyBtn")
        {
            //向服务器发送准备信息
            readyBtn.SetActive(false);
            PaiRoundReadyRequest message = new PaiRoundReadyRequest { };
            SocketManager socketManager = SocketManager.Instance;
            socketManager.SendProtobuf1(message, MsgId.PaiRoundReadyRequest);
        }
        else if (Btn.name == "QiangZhuangBtn")
        {
            //抢庄请求
            QiangZhuang.SetActive(false);
            PaiGrabMasterRequest message = new PaiGrabMasterRequest { };
            SocketManager socketManager = SocketManager.Instance;
            socketManager.SendProtobuf1(message, MsgId.PaiGrabMasterRequest);
        }
        else if(Btn.name == "setSaizi")//掷骰子请求操作
        {
            SetSaizi.SetActive(false);
            PaiThrowDiceRequest message = new PaiThrowDiceRequest { };
            SocketManager socketManager = SocketManager.Instance;
            socketManager.SendProtobuf1(message, MsgId.PaiThrowDiceRequest);
        }      
        else if (Btn.name == "ShunMen")
        {                        
            Direction = 1;
            ownChipsCountList[0] += xtj.currentChip;
            PaiBetRequest(xtj.currentChip, Direction);            
        }
        else if (Btn.name == "Tang")
        {            
            Direction = 2;
            ownChipsCountList[1] += xtj.currentChip;
            PaiBetRequest(xtj.currentChip, Direction);            
        }
        else if (Btn.name == "Daomen")
        {                        
            Direction = 3;
            ownChipsCountList[2] += xtj.currentChip;
            PaiBetRequest(xtj.currentChip, Direction);            
        }
        else if (Btn.name == "Daojiao")
        {                       
            Direction = 4;
            ownChipsCountList[3] += xtj.currentChip;
            PaiBetRequest(xtj.currentChip, Direction);            
        }
        else if (Btn.name == "Tianmen")
        {                       
            Direction = 5;
            ownChipsCountList[4] += xtj.currentChip;
            PaiBetRequest(xtj.currentChip, Direction);            
        }
        else if (Btn.name == "ShunJiao")
        {                      
            Direction = 6;
            ownChipsCountList[5] += xtj.currentChip;
            PaiBetRequest(xtj.currentChip, Direction);            
        }

    }
    void PaiBetRequest(long coin, int dir)
    {
        Debug.Log("下注请求,下注金币是：" + coin + ",下注方位是：" + dir);
        PaiBetRequest message = new PaiBetRequest { Coin = coin, Direction = dir };
        SocketManager socketManager = SocketManager.Instance;
        socketManager.SendProtobuf1(message, MsgId.PaiBetRequest);
    }

    public override void SocketReceiveMessage(byte[] data)
    {
        base.SocketReceiveMessage(data);
        byte[] dataLength = data.Skip(0).Take(2).ToArray();
        byte[] dataId = data.Skip(2).Take(4).ToArray();
        byte[] dataConcent = data.Skip(data.Length - (data.Length - 4)).ToArray();
        int TempMsgID = ProtoDataToMsg.Byte2ushort(dataId);

        //加入房间
        if (TempMsgID == MsgId.PaiEnterRoundBroadcast)
        {
            Pb.PaiEnterRoundBroadcast newpb = Pb.PaiEnterRoundBroadcast.Parser.ParseFrom(dataConcent);            
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);
            Debug.Log("有玩家加入房间了");
            //if (newpb.Status == (int)STATUS.Success)
            {
                if(uid != newpb.Round.NewPlayer.Id){

                    xtj.playersList.Add(newpb.Round.NewPlayer);
                    xtj.SortPlayer();
                    //求得新加入的玩家在房间中的位置
                    int tempIndex = xtj.ReturnPlayerSeat(newpb.Round.NewPlayer.Id);
                    Debug.Log("新加入房间的玩家的tempIndex = " + tempIndex);
                    if (newpb.Round.NewPlayer.AvatarUrl != "")
                    {
                        WXAvatarManager._instance.GetWxAvatar(newpb.Round.NewPlayer.Id, xtjUsers[tempIndex].wxAvatar, newpb.Round.NewPlayer.AvatarUrl);
                        xtjUsers[tempIndex].wxAvatar.gameObject.SetActive(true);
                    }
                    else
                    {
                        xtjUsers[tempIndex].avatar.spriteName = newpb.Round.NewPlayer.AvatarId.ToString();
                        xtjUsers[tempIndex].avatar.gameObject.SetActive(true);
                    }
                    xtjUsers[tempIndex].goldLabel.text = user.ReturnMoneyForLong(newpb.Round.NewPlayer.Coin);
                    xtjUsers[tempIndex].uid = newpb.Round.NewPlayer.Id;    
                }
            }
        }
        //自己离开房间
        else if (TempMsgID == MsgId.PaiLeaveRoundResponse)
        {
            Pb.PaiLeaveRoundResponse newpb = Pb.PaiLeaveRoundResponse.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);
            if(newpb.Status == (int)STATUS.Success){
                xtj.playersList.Clear();
                if (uid == xtj.bankerId)
                {
                    xtj.bankerId = 0;
                }
                for (int i = 0; i < xtjUsers.Count; i++)
                {
                    xtjUsers[i].InitPlayer();
                }
                SceneManager.LoadSceneAsync(ScenePath.Hall);
            }
            else
            {
                user.logMsg = newpb.Msg;
                GameObject msg = NGUITools.AddChild(Root,(GameObject)Resources.Load("LogMsg"));
            }
        }
        //玩家离开房间
        else if (TempMsgID == MsgId.PaiLeaveRoundBroadcast)
        {
            Pb.PaiLeaveRoundBroadcast newpb = Pb.PaiLeaveRoundBroadcast.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);
            Debug.Log("有玩家离开房间了");
            //求得离开玩家在房间中位置
            int tempIndex = xtj.ReturnPlayerSeat(newpb.PlayerId);
            xtjUsers[tempIndex].InitPlayer();
        }
        else if (TempMsgID == MsgId.PaiRoundReadyBroadcast)//通知玩家开始准备
        {
            Pb.PaiRoundReadyBroadcast newpb = Pb.PaiRoundReadyBroadcast.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);
            Debug.Log("接收到服务器发送的准备通知");
            readyBtn.SetActive(true);
            //播放开始游戏音效
            SoundModel.PlaySound(effectBgList[4]);
            //RecoverInit();
        }
        else if (TempMsgID == MsgId.PaiRoundReadyResponse)
        {
            Pb.PaiRoundReadyResponse newpb = Pb.PaiRoundReadyResponse.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);
            if (newpb.Status == (int)STATUS.Success)
            {
                //readyBtn.SetActive(true);
            }
            else
            {
                user.logMsg = newpb.Msg;
                GameObject msg = NGUITools.AddChild(Root, (GameObject)Resources.Load("LogMsg"));
            }
        }

        else if (TempMsgID == MsgId.PaiRoundReadyResultBroadcast)//通知玩家已经准备上了
        {
            Pb.PaiRoundReadyResultBroadcast newpb = Pb.PaiRoundReadyResultBroadcast.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);
            int tempIndex = xtj.ReturnPlayerSeat(newpb.PlayerId);
            xtjUsers[tempIndex].readyStatus.SetActive(true);
            if (uid == newpb.PlayerId)
            {
                readyBtn.SetActive(false);
            }
            
        }
        else if (TempMsgID == MsgId.PaiGrabMasterBroadcast)//开始抢庄
        {
            Pb.PaiGrabMasterBroadcast newpb = Pb.PaiGrabMasterBroadcast.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);
            Debug.Log("开始抢庄");
            for (int i = 0; i < xtjUsers.Count;i++ )
            {
                xtjUsers[i].readyStatus.SetActive(false);
            }
            readyBtn.SetActive(false);
            QiangZhuang.SetActive(true);

            xtj.grabMasterList = newpb.Players.ToList();                   
        }
        //抢庄响应
        else if (TempMsgID == MsgId.PaiGrabMasterResponse)
        {
            Pb.PaiGrabMasterResponse newpb = Pb.PaiGrabMasterResponse.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);
            if (newpb.Status == (int)STATUS.Success)
            {

            }
            else
            {
                user.logMsg = newpb.Msg;
                GameObject msg = NGUITools.AddChild(Root, (GameObject)Resources.Load("LogMsg"));
            }
        }
        else if (TempMsgID == MsgId.PaiGrabMasterResultBroadcast)//抢庄结果信息
        {            
            Pb.PaiGrabMasterResultBroadcast newpb = Pb.PaiGrabMasterResultBroadcast.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);

            QiangZhuang.SetActive(false);
            if(uid == newpb.PlayerId){
                xtj.isBanker = true;
            }
            StartCoroutine(QiangBanker(xtj.grabMasterList,newpb.PlayerId));
            
        }
        else if(TempMsgID == MsgId.PaiThrowDiceBroadcast)//通知掷骰子
        {
            Pb.PaiThrowDiceBroadcast newpb = Pb.PaiThrowDiceBroadcast.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);
            Debug.Log("通知掷骰子");
            if(xtj.isBanker == true)
            {
                SetSaizi.SetActive(true);
            }
        }
        //掷骰子响应
        else if (TempMsgID == MsgId.PaiThrowDiceResponse)
        {
            Pb.PaiThrowDiceResponse newpb = Pb.PaiThrowDiceResponse.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);
            if (newpb.Status == (int)STATUS.Success)
            {

            }
            else
            {
                user.logMsg = newpb.Msg;
                GameObject msg = NGUITools.AddChild(Root, (GameObject)Resources.Load("LogMsg"));
            }
        }
        else if (TempMsgID == MsgId.PaiThrowDiceResultBroadcast)//開始擲骰子操作
        {
            Pb.PaiThrowDiceResultBroadcast newpb = Pb.PaiThrowDiceResultBroadcast.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);
            SetSaizi.SetActive(false);
            GameObject dice = NGUITools.AddChild(Root,(GameObject)Resources.Load(GameXTJPrafabPath.Shaizi));
            DiceModel diceModel = dice.GetComponent<DiceModel>();
            diceModel.diceAniObj.SetActive(true);
            diceSum = newpb.Points[0] + newpb.Points[1];
            //播放掷骰子音效
            SoundModel.PlaySound(effectBgList[5]);
            StartCoroutine(DiceAnimation(diceModel,newpb.Points.ToList()));
            
        }
        else if (TempMsgID == MsgId.PaiDealCardBroadcast)//进行发牌操作
        {
            Pb.PaiDealCardBroadcast newpb = Pb.PaiDealCardBroadcast.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);
            //销毁筛子
            GameObject dice = GameObject.Find("UI Root/Shaizi");
            if(dice != null){
                Destroy(dice);
            }            
             
            //计算发牌顺序
            SortDealCards();
            //发牌
            StartCoroutine(CloneCards(newpb));
            
        }
        else if (TempMsgID == MsgId.PaiBetBroadcast)//开始进行下注操作
        {
            Pb.PaiBetResultBroadcast newpb = Pb.PaiBetResultBroadcast.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);

            QiangZhuang.SetActive(false);
            Debug.Log("执行开始下注操作");
            //加载下注时间
            GameObject betTime = NGUITools.AddChild(Root,(GameObject)Resources.Load(GameXTJ100PrefabPath.BetTime));
            //加载筹码按钮
            if(xtj.isBanker == false){
                GameObject chips = NGUITools.AddChild(Root,(GameObject)Resources.Load(GameXTJPrafabPath.Chips));
                chips.transform.localPosition = new Vector3(22,-278,0);
                xtj.currentChip = xtj.chipList[0];
            }

            //播放开始下注音效
            SoundModel.PlaySound(effectBgList[0]);

        }
        //下注响应
        else if (TempMsgID == MsgId.PaiBetResponse)
        {
            Pb.PaiBetResponse newpb = Pb.PaiBetResponse.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);
            if (newpb.Status == (int)STATUS.Success)
            {

            }
            else
            {
                user.logMsg = newpb.Msg;
                GameObject msg = NGUITools.AddChild(Root, (GameObject)Resources.Load("LogMsg"));
            }
        }
        else if (TempMsgID == MsgId.PaiBetResultBroadcast)//有玩家进行下注操作
        {
            Pb.PaiBetResultBroadcast newpb = Pb.PaiBetResultBroadcast.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);
            //if (newpb.Status == (int)STATUS.Success)
            {

                //克隆筹码
                CloneChips(newpb.PlayerId, newpb.Direction,newpb.Coin);

                //显示各个位置的总筹码数
                foreach(KeyValuePair<int,long> keyValue in newpb.AllPlayerCoinMap){
                    if(keyValue.Key == 1){
                        poolChipsCountLabels[0].text = newpb.AllPlayerCoinMap[1].ToString();
                    }
                    else if(keyValue.Key == 2)
                    {
                        poolChipsCountLabels[1].text = newpb.AllPlayerCoinMap[2].ToString();
                    }
                    else if (keyValue.Key == 3)
                    {
                        poolChipsCountLabels[2].text = newpb.AllPlayerCoinMap[3].ToString();
                    }
                    else if (keyValue.Key == 4)
                    {
                        poolChipsCountLabels[3].text = newpb.AllPlayerCoinMap[4].ToString();
                    }
                    else if (keyValue.Key == 5)
                    {
                        poolChipsCountLabels[4].text = newpb.AllPlayerCoinMap[5].ToString();
                    }
                    else if (keyValue.Key == 6)
                    {
                        poolChipsCountLabels[5].text = newpb.AllPlayerCoinMap[6].ToString();
                    }
                }
                //显示自己在各个位置所下的筹码数
                if(uid == newpb.PlayerId){
                    foreach (KeyValuePair<int, long> keyValue in newpb.CurrentPlayerCoinMap)
                    {
                        if (keyValue.Key == 1)
                        {
                            ownChipsCountLabels[0].text = newpb.CurrentPlayerCoinMap[1].ToString();
                        }
                        else if (keyValue.Key == 2)
                        {
                            ownChipsCountLabels[1].text = newpb.CurrentPlayerCoinMap[2].ToString();
                        }
                        else if (keyValue.Key == 3)
                        {
                            ownChipsCountLabels[2].text = newpb.CurrentPlayerCoinMap[3].ToString();
                        }
                        else if (keyValue.Key == 4)
                        {
                            ownChipsCountLabels[3].text = newpb.CurrentPlayerCoinMap[4].ToString();
                        }
                        else if (keyValue.Key == 5)
                        {
                            ownChipsCountLabels[4].text = newpb.CurrentPlayerCoinMap[5].ToString();
                        }
                        else if (keyValue.Key == 6)
                        {
                            ownChipsCountLabels[5].text = newpb.CurrentPlayerCoinMap[6].ToString();
                        }
                    }
                }

                //更新玩家的金币数
                int tempIndex = xtj.ReturnPlayerSeat(newpb.PlayerId);
                xtjUsers[tempIndex].goldLabel.text = user.ReturnMoneyForLong(newpb.RestCoin);                            
            }
            //else
            //{
            //    user.logMsg = newpb.Msg;
            //    GameObject msg = NGUITools.AddChild(Root, (GameObject)Resources.Load("LogMsg"));
            //}
            
        }
        else if(TempMsgID == MsgId.PaiBetStopBroadcast)//停止押注
        {
            Pb.PaiBetStopBroadcast newpb = Pb.PaiBetStopBroadcast.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);

            //显示停止下注
            stopBet.SetActive(true);
            //播放停止下注音效
            SoundModel.PlaySound(effectBgList[2]);

            StartCoroutine(HideStopBet());
       
            //销毁筹码面板
            GameObject chipPanel = GameObject.Find("UI Root/Chips");
            if(chipPanel != null){
                Destroy(chipPanel);
            }
        }
        else if(TempMsgID == MsgId.PaiLeaveRoundResponse)//请求离开返回
        {
            Pb.PaiLeaveRoundResponse newpb = Pb.PaiLeaveRoundResponse.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);
            if (newpb.Status == 1)//1代表成功
            {
                xtj.playersList.Clear();
                xtj.bankerId = 0;
                SceneManager.LoadSceneAsync(ScenePath.Hall);
            }
            else
            {
                user.logMsg = newpb.Msg;
                NGUITools.AddChild(this.gameObject, (GameObject)(Resources.Load("LogMsg")));
            }

        }
      
        else if (TempMsgID == MsgId.PaiKickOutRoundBroadcast)//被踢出去的玩家的广播
        {
            Pb.PaiKickOutRoundBroadcast newpb = Pb.PaiKickOutRoundBroadcast.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);
            Debug.Log(user.Uid);
            if (newpb.PlayerId.ToString()==user.Uid)
            {
                //user.zhunbei = false;
                xtj.playersList.Clear();
                xtjUsers[0].InitPlayer();
                SceneManager.LoadSceneAsync(ScenePath.Hall);
            }
            else
            {
                //得出其他人在房间中的位置
                int tempIndex = xtj.ReturnPlayerSeat(newpb.PlayerId);
                xtjUsers[tempIndex].InitPlayer();
            }
        }
        else if (TempMsgID == MsgId.PaiGameOverBroadcast)//一局结束后的广播
        {
            //区分金币场和房间场做相应的反应
        }
       
         //网络异常
        else if (TempMsgID == MsgId.NetWorkAbnormalMessage)
        {
            GameObject NetWorkAbnormal = NGUITools.AddChild(GameObject.Find("UI Root"), (GameObject)(Resources.Load("NetWorkAbnormal")));
        }
    
    }
         
    /// <summary>
    /// 加载玩家信息
    /// </summary>
    void LoadUser()
    {
        #region
        //Debug.Log("进入房间，加载玩家" + xtj.playersList.Count);
        //for (int i = 0; i < xtj.playersList.Count; i++)
        //{
        //    //显示自己
        //    if (int.Parse(user.Uid) == xtj.playersList[i].Id)
        //    {
        //        if (user.loginControl == 1)
        //        {
        //            WXAvatarManager._instance.GetWxAvatar(xtj.playersList[i].Id, xtjUsers[0].wxAvatar, xtj.playersList[i].AvatarUrl);
        //            xtjUsers[0].wxAvatar.gameObject.SetActive(true);
        //        }
        //        else
        //        {
        //            xtjUsers[0].avatar.spriteName = xtj.playersList[i].AvatarId.ToString();
        //            xtjUsers[0].avatar.gameObject.SetActive(true);
        //        }
        //        xtjUsers[0].goldLabel.text = user.ReturnMoneyForLong(xtj.playersList[i].Coin);
        //        xtjUsers[0].uid = int.Parse(user.Uid);
        //    }
        //    else
        //    {
        //        //显示其他玩家
        //        for (int j = 1; j < xtj.playersList.Count; j++)
        //        {
        //            if (xtj.playersList[i].AvatarUrl != "")
        //            {
        //                WXAvatarManager._instance.GetWxAvatar(xtj.playersList[i].Id, xtjUsers[j].wxAvatar, xtj.playersList[i].AvatarUrl);
        //                xtjUsers[j].wxAvatar.gameObject.SetActive(true);
        //            }
        //            else
        //            {
        //                xtjUsers[j].avatar.spriteName = xtj.playersList[i].AvatarId.ToString();
        //                xtjUsers[j].avatar.gameObject.SetActive(true);
        //            }
        //            xtjUsers[j].goldLabel.text = user.ReturnMoneyForLong(xtj.playersList[i].Coin);
        //            xtjUsers[j].uid = xtj.playersList[i].Id;
        //        }
        //    }
        //}

        ////显示庄家信息
        //for (int i = 0; i < xtj.playersList.Count; i++)
        //{
        //    if(xtjUsers[i].uid == xtj.bankerInfo.Id){
        //        xtjUsers[i].bankerIcon.SetActive(true);
        //        xtjUsers[i].QiangZhuangStatus.SetActive(true);
        //    }
        //}
        #endregion

        Debug.Log("进入房间，加载玩家" + xtj.playersList.Count);
        xtj.SortPlayer();
        for (int i = 0; i < xtj.playersList.Count; i++)
        {
            //求得房间中的玩家在房间中的位置
            int tempIndex = xtj.ReturnPlayerSeat(xtj.playersList[i].Id);
            if (xtj.playersList[i].AvatarUrl != "")
            {
                WXAvatarManager._instance.GetWxAvatar(xtj.playersList[i].Id, xtjUsers[tempIndex].wxAvatar, xtj.playersList[i].AvatarUrl);
                xtjUsers[tempIndex].wxAvatar.gameObject.SetActive(true);
            }
            else
            {
                xtjUsers[tempIndex].avatar.spriteName = xtj.playersList[i].AvatarId.ToString();
                xtjUsers[tempIndex].avatar.gameObject.SetActive(true);
            }
            xtjUsers[tempIndex].goldLabel.text = user.ReturnMoneyForLong(xtj.playersList[i].Coin);
            xtjUsers[tempIndex].uid = int.Parse(user.Uid);

        }

        //显示庄家信息      
        //求得庄家在房间中的位置
        if (xtj.bankerId != 0)
        {
            int tempIndex1 = xtj.ReturnPlayerSeat(xtj.bankerId);
            xtjUsers[tempIndex1].QiangZhuangStatus.SetActive(true);
            xtjUsers[tempIndex1].bankerIcon.SetActive(true);
        }


        //显示各个方位的总筹码数
        for (int i = 0; i < xtj.newpb.AllChips.Count; i++)
        {
            KeyValuePair<int, PaiInt64Array> keyValue = xtj.newpb.AllChips.ElementAt(i);
            long sum = 0;
            for (int j = 0; j < keyValue.Value.Value.Count; j++)
            {
                ReconnectCloneChip(keyValue.Value.Value.Count, keyValue.Value.Value[j], keyValue.Key);
                sum += keyValue.Value.Value[j];
            }
            poolChipsCountLabels[keyValue.Key - 1].text = sum.ToString();
        }
        //显示自己在各个方位下的筹码数
        for (int i = 0; i < xtj.newpb.SelfChips.Count; i++)
        {
            KeyValuePair<int, PaiInt64Array> keyValue = xtj.newpb.SelfChips.ElementAt(i);
            long ownSum = 0;
            for (int j = 0; j < keyValue.Value.Value.Count; j++)
            {
                ownSum += keyValue.Value.Value[j];
            }
            ownChipsCountLabels[keyValue.Key - 1].text = ownSum.ToString();
        }

        //显示当前发的牌
        if (xtj.newpb.CardMap.Count > 0)
        {
            GameObject cardsPanel = NGUITools.AddChild(Root,(GameObject)Resources.Load(GameXTJPrafabPath.CardsPanel));            
            for (int i = 0; i < xtj.newpb.CardMap.Count; i++)
            {
                KeyValuePair<int, PaiCardGroup> keyValue = xtj.newpb.CardMap.ElementAt(i);
                GameObject cardItem = Instantiate(cardsPre);
                cardItem.transform.parent = cardsPanel.transform;
                cardItem.transform.localScale = Vector3.one;
                cardItem.transform.localPosition = new Vector3(0, 296, 0);
                Cards cards = cardItem.GetComponent<Cards>();
                if (keyValue.Key == 1)
                {
                    cardItem.transform.localPosition = ShunMen.transform.localPosition;
                }
                else if (keyValue.Key == 2)
                {
                    cardItem.transform.localPosition = Tang.transform.localPosition;
                }
                else if (keyValue.Key == 3)
                {
                    cardItem.transform.localPosition = Daomen.transform.localPosition;
                }
                else if (keyValue.Key == 5)
                {
                    cardItem.transform.localPosition = Tianmen.transform.localPosition;
                }
                cards.destination = cardItem.transform.localPosition;
                cards.ShowCards(keyValue.Value.Cards.ToList(), keyValue.Value.Form);
                
            }
        }

        //显示一局结束之后的分数和金币数
        if (xtj.newpb.CoinMap.Count > 0)
        {
            GameObject gameOverPanel = NGUITools.AddChild(Root, (GameObject)Resources.Load(GameXTJPrafabPath.GameOver));
            GameOver gameOver = gameOverPanel.GetComponent<GameOver>();
            for (int i = 0; i < xtj.newpb.CoinMap.Count; i++)
            {
                KeyValuePair<int, PaiInt64Array> keyValue = xtj.newpb.CoinMap.ElementAt(i);
                //求得玩家在房间中对应的位置
                int tempIndex = xtj.ReturnPlayerSeat(keyValue.Key);
                //显示输赢的金币数
                gameOver.ShowScore(keyValue.Value.Value[0], gameOver.ScoreSprites[tempIndex], gameOver.ScoreFathers[tempIndex], gameOver.JiaJians[tempIndex]);
                //显示剩余的金币数
                xtjUsers[tempIndex].goldLabel.text = EginUser.Instance.ReturnMoneyForLong(keyValue.Value.Value[1]);

                if (int.Parse(EginUser.Instance.Uid) == keyValue.Key)
                {
                    EginUser.Instance.coinCount = keyValue.Value.Value[1].ToString();
                }
            }
        }

    }

    /// <summary>
    /// 抢庄闪烁动画
    /// </summary>
    /// <param name="grabMasterList"></param>
    /// <param name="bankerId"></param>
    /// <returns></returns>
    IEnumerator QiangBanker(List<int> grabMasterList,int bankerId)
    {
        List<int> indexList = new List<int>();
        int tempInt = 0;
        
        for (int j = 0; j < grabMasterList.Count; j++)
        {
            //求得参与抢庄的人的在房间中的位置
            int tempIndex = xtj.ReturnPlayerSeat(grabMasterList[j]);
            indexList.Add(tempIndex);
            Debug.Log("参与抢庄的人在房间中的位置：" + tempIndex);
        }
        
       
        
        //闪烁
        for (int i = 0; i < 10;i++ )
        {
            for (int j = 0; j < indexList.Count; j++)
            {
                xtjUsers[tempInt].QiangZhuangStatus.SetActive(false);
                tempInt = indexList[j];
                xtjUsers[tempInt].QiangZhuangStatus.SetActive(true);
                yield return new WaitForSeconds(0.05f);
            }
        }

        for (int i = 0; i < xtjUsers.Count;i++ )
        {
            xtjUsers[i].QiangZhuangStatus.SetActive(false);
        }
        //显示庄家信息
        //得到庄家在房间中的位置
        int bankerIndex = xtj.ReturnPlayerSeat(bankerId);
        xtjUsers[bankerIndex].bankerIcon.SetActive(true);
        xtjUsers[bankerIndex].QiangZhuangStatus.SetActive(true);


    }


    IEnumerator DiceAnimation(DiceModel diceModel,List<int> points)
    {
        yield return new WaitForSeconds(1.5f);
        diceModel.diceAniObj.SetActive(false);
        diceModel.dice1.spriteName = "shaizi" + points[0].ToString();
        diceModel.dice2.spriteName = "shaizi" + points[1].ToString();
        diceModel.dice1.gameObject.SetActive(true);
        diceModel.dice2.gameObject.SetActive(true);
    }

    /// <summary>
    /// 克隆筹码
    /// </summary>
    public void CloneChips(int id,int direction,long chipCoin)
    {
        Vector3 tempPos = new Vector3();
        GameObject chip = Instantiate(ChipPre);
        chip.transform.SetParent(chipParent.transform);
        chip.transform.localScale = new Vector3(0.6f,0.6f,1);
        Debug.Log("筹码图片名称：" + xtj.level + "_" + (chipCoin / 10000));
        chip.GetComponent<UISprite>().spriteName = xtj.level + "_" + (chipCoin / 10000);
        //确定是谁下的注
        //得到下注人在房间中的位置
        int tempIndex = xtj.ReturnPlayerSeat(id);
        chip.transform.localPosition = xtjUsers[tempIndex].transform.localPosition;

        //确定移动的终点
        if(direction == 1){
            tempPos = new Vector3(Random.Range(-318,-152),Random.Range(0,88),0);
        }
        else if (direction == 2)
        {
            tempPos = new Vector3(Random.Range(-76, 114), Random.Range(75, 88), 0);
        }
        else if (direction == 3)
        {
            tempPos = new Vector3(Random.Range(187, 350), Random.Range(0, 88), 0);
        }
        else if (direction == 4)
        {
            tempPos = new Vector3(Random.Range(186, 310), Random.Range(-135, -115), 0);
        }
        else if (direction == 5)
        {
            tempPos = new Vector3(Random.Range(-78, 112), Random.Range(-140, -97), 0);
        }
        else if (direction == 6)
        {
            tempPos = new Vector3(Random.Range(-303, -152), Random.Range(-140, -115), 0);
        }
        ChipsMove chipsMove = chip.GetComponent<ChipsMove>();
        chipsMove.destination = tempPos;
        chip.SetActive(true);

        //播放加注音效
        SoundModel.PlaySound(effectBgList[1]);
    }

    /// <summary>
    /// 确定发牌的顺序
    /// </summary>
    /// <returns></returns>
    public void SortDealCards()
    {       
        int num = diceSum % 4;
        if(num == 0)
        {
            dealCardsPosDic.Add(2,Tang);
            dealCardsPosDic.Add(1, ShunMen);
            dealCardsPosDic.Add(5, Tianmen);
            dealCardsPosDic.Add(3, Daomen);
        }
        else if (num == 1)
        {            
            dealCardsPosDic.Add(1, ShunMen);
            dealCardsPosDic.Add(5, Tianmen);
            dealCardsPosDic.Add(3, Daomen);
            dealCardsPosDic.Add(2, Tang);
        }
        else if (num == 2)
        {            
            dealCardsPosDic.Add(5, Tianmen);
            dealCardsPosDic.Add(3, Daomen);
            dealCardsPosDic.Add(2, Tang);
            dealCardsPosDic.Add(1, ShunMen);
        }
        else if (num == 3)
        {
            dealCardsPosDic.Add(3, Daomen);
            dealCardsPosDic.Add(2, Tang);
            dealCardsPosDic.Add(1, ShunMen);
            dealCardsPosDic.Add(5, Tianmen);          
        }      
    }

    /// <summary>
    /// 克隆牌
    /// </summary>
    /// <param name="newpb"></param>
    /// <returns></returns>
    IEnumerator CloneCards(PaiDealCardBroadcast newpb)
    {
        dealCardsDic.Clear();
        //播放开始发牌音效
        SoundModel.PlaySound(effectBgList[3]);

        GameObject cardsPanel = NGUITools.AddChild(Root,(GameObject)Resources.Load(GameXTJPrafabPath.CardsPanel));
        for (int i = 0; i < dealCardsPosDic.Count;i++ )
        {
            GameObject cardsObj = Instantiate(cardsPre);
            cardsObj.transform.SetParent(cardsPanel.transform);
            cardsObj.transform.localScale = Vector3.one;
            cardsObj.transform.localPosition = new Vector3(0,296,0);
            Cards cards = cardsObj.GetComponent<Cards>();
            KeyValuePair<int,GameObject> element = dealCardsPosDic.ElementAt(i);
            cards.destination = element.Value.transform.localPosition;
            dealCardsDic.Add(element.Key,cardsObj);
            yield return new WaitForSeconds(0.5f);
        }

        StartCoroutine(ShowCards(newpb));  
    }

    /// <summary>
    /// 展示牌
    /// </summary>
    /// <param name="newpb"></param>
    /// <returns></returns>
    IEnumerator ShowCards(PaiDealCardBroadcast newpb)
    {
        yield return new WaitForSeconds(2f);
        for (int i = 0; i < dealCardsPosDic.Count;i++ )
        {
            KeyValuePair<int, GameObject> element = dealCardsDic.ElementAt(i);
            foreach (KeyValuePair<int,PaiCardGroup> keyValue in newpb.CardMap)
            {
                if(element.Key == keyValue.Key)
                {
                    Cards cards = element.Value.GetComponent<Cards>();
                    cards.ShowCards(newpb.CardMap[keyValue.Key].Cards.ToList(), newpb.CardMap[keyValue.Key].Form);
                }
            }
            yield return new WaitForSeconds(0.5f);
        }

        //加载游戏结束面板
        GameObject gameOverPanel = NGUITools.AddChild(Root, (GameObject)Resources.Load(GameXTJPrafabPath.GameOver));
        GameOver gameOver = gameOverPanel.GetComponent<GameOver>();
        gameOver.newpb = newpb;
    }


    /// <summary>
    /// 恢复初始状态
    /// </summary>
    public void RecoverInit()
    {
        //玩家恢复
        for (int i = 0; i < xtjUsers.Count;i++ )
        {
            xtjUsers[i].readyStatus.SetActive(false);
            xtjUsers[i].QiangZhuangStatus.SetActive(false);
            xtjUsers[i].bankerIcon.SetActive(false);
        }

        //筹码销毁
        for (int i = 0; i < chipParent.transform.childCount;i++ )
        {
            Destroy(chipParent.transform.GetChild(i).gameObject);
        }
        //筹码数置空
        for (int i = 0; i < poolChipsCountLabels.Count;i++ )
        {
            poolChipsCountLabels[i].text = "";
            ownChipsCountLabels[i].text = "";
            ownChipsCountList[i] = 0;
        }

        xtj.bankerId = 0;
        xtj.isReady = false;
        xtj.isBanker = false;
        dealCardsDic.Clear();
        dealCardsPosDic.Clear();
    }

    /// <summary>
    /// 隐藏停止下注显示框
    /// </summary>
    /// <returns></returns>
    IEnumerator HideStopBet()
    {
        yield return new WaitForSeconds(1f);
        stopBet.SetActive(false);
    }

    /// <summary>
    /// 重连克隆筹码
    /// </summary>
    void ReconnectCloneChip(int count, long spriteNameId, int direction)
    {
        Vector3 tempPos = new Vector3();
        //for (int i = 0; i < count; i++)
        {
            GameObject chip = Instantiate(ChipPre);
            chip.transform.parent = chipParent.transform;          
            Debug.Log("筹码图片名称：" + xtj.level + "_" + (spriteNameId / 10000));
            chip.GetComponent<UISprite>().spriteName = xtj.level + "_" + (spriteNameId / 10000);
            chip.GetComponent<UISprite>().MakePixelPerfect();
            chip.transform.localScale = new Vector3(0.6f, 0.6f, 1);

            //确定移动的终点
            if (direction == 1)
            {
                tempPos = new Vector3(Random.Range(-318, -152), Random.Range(0, 88), 0);
            }
            else if (direction == 2)
            {
                tempPos = new Vector3(Random.Range(-76, 114), Random.Range(75, 88), 0);
            }
            else if (direction == 3)
            {
                tempPos = new Vector3(Random.Range(187, 350), Random.Range(0, 88), 0);
            }
            else if (direction == 4)
            {
                tempPos = new Vector3(Random.Range(186, 310), Random.Range(-135, -115), 0);
            }
            else if (direction == 5)
            {
                tempPos = new Vector3(Random.Range(-78, 112), Random.Range(-140, -97), 0);
            }
            else if (direction == 6)
            {
                tempPos = new Vector3(Random.Range(-303, -152), Random.Range(-140, -115), 0);
            }
            ChipsMove chipsMove = chip.GetComponent<ChipsMove>();
            chip.transform.localPosition = tempPos;
            chipsMove.destination = tempPos;
            chip.SetActive(true);
        }
    }
}
